package cz.muni.fi.pa165.pokemon.dao.impl;

import cz.muni.fi.pa165.pokemon.dao.TrainerDAO;
import cz.muni.fi.pa165.pokemon.entity.Trainer;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Jan Koščák (xkoscak@gmail.com)
 */
@Repository
public class TrainerDAOImpl implements TrainerDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void create(Trainer trainer) {
        if (trainer == null) {
            throw new IllegalArgumentException("trainer is null");
        }        
        if (trainer.getId() != null) {
            throw new IllegalArgumentException("trainer.id is not null");
        }
        em.persist(trainer);
    }

    @Override
    public Trainer get(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("id is null");
        }
        Trainer result = em.find(Trainer.class, id);
        return result;
    }

    @Override
    public void update(Trainer trainer) {
        if (trainer == null) {
            throw new IllegalArgumentException("trainer is null");
        }
        if (trainer.getId() == null) {
            throw new IllegalArgumentException("trainer id is null");
        }
        em.merge(trainer);
    }

    @Override
    public void remove(Trainer trainer) {
        if (trainer == null) {
            throw new IllegalArgumentException("trainer is null");
        }
        if (trainer.getId() == null) {
            throw new IllegalArgumentException("trainer.id is null");
        }
        Trainer toRemove = em.find(Trainer.class, trainer.getId());
        if (toRemove == null) {
            throw new IllegalArgumentException("trainer does not exist");
        }
        em.remove(toRemove);
    }

    @Override
    public List<Trainer> findAll() {
        TypedQuery<Trainer> tq = em.createQuery("FROM Trainer", Trainer.class);
        List<Trainer> result = tq.getResultList();
        
        return result;
    }

    @Override
    public List<Trainer> findByName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        TypedQuery<Trainer> tq = em.createQuery("SELECT t FROM Trainer t WHERE t.name LIKE :name", Trainer.class);
        tq.setParameter("name", name);
        List<Trainer> result = tq.getResultList();
        
        return result;
    }
}
